#include "joinRoomCommand.h"

QDomDocument JoinRoomCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result;

    if (this->isAuthorized(doc)) {
        QDomNodeList roomNodes = doc.elementsByTagName("room");
        if (roomNodes.count() == 1) {
            QString roomName = roomNodes.at(0).toElement().text().trimmed();
            if (this->isLoginCorrect(roomName)) {
                User* me = this->getCurrentUser(doc);
                result = this->processRoomName(me, roomName, doc);
            } else {
                result = "<joinRoom><success>FALSE</success><reason>WRONG_ROOM_NAME</reason></joinRoom>";
            }
        } else {
            result = "<joinRoom><success>FALSE</success><reason>WRONG_XML</reason></joinRoom>";
        }
    } else {
        result = "<joinRoom><success>FALSE</success><reason>NOT_AUTHORIZED</reason></joinRoom>";
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}


QString JoinRoomCommand::processRoomName(User* me, QString roomName, QDomDocument doc) {
    QString result = "<joinRoom><success>TRUE</success>";
    Room* room = DB::getInstance()->findRoom(roomName);
    QDomNodeList passNodes = doc.elementsByTagName("roomPassHash");
    if (room == NULL) {
        room = new Room(me->getIdentify(), roomName);        
        if (passNodes.count()) {
            QString passHash = passNodes.at(0).toElement().text().trimmed();
            room->setPass(passHash);
        }
        DB::getInstance()->addRoom(room);
        result.append("<rule>OWNER</rule><roomDescription></roomDesription>");
    } else {
        if (room->getPassNeed()) {
            if (!passNodes.count() || passNodes.at(0).toElement().text().compare(room->getPassHash()) != 0) {
                return "<joinRoom><success>FALSE</success><reason>WRONG_PASS_FOR_ROOM</reason></joinRoom>";
            }
        }
        if (room->isOwner(me)) {
            result.append("<rule>OWNER</rule>");
        } else {
            if (room->isModerator(me)) {
                result.append("<rule>MODERATOR</rule>");
            } else {
                result.append("<rule>USER</rule>");
            }
        }
        result.append("<roomDescription>").append( room->getDescription() ).append("</roomDesription>");
    }
    room->addUser(me);
    return result.append("</joinRoom>");
}
